import React, { useRef, useState } from 'react';
import { ProTable } from '@ant-design/pro-components';
import { Button, message, Drawer, Tooltip, Badge, Space, Typography, Card } from 'antd';
import { PlusOutlined, EditOutlined, DeleteOutlined, SyncOutlined, QuestionCircleOutlined, BarChartOutlined, ArrowLeftOutlined } from '@ant-design/icons';
import { PageContainer } from '@ant-design/pro-layout';
import { PAGE, DEL } from '@/services/crud';
import DatabaseConfigForm from './DatabaseConfigForm';
import { history } from 'umi';

const { Text, Link } = Typography;

const DATABASE_CONFIG_URL = '/api/database-configs';

interface DatabaseConfigItem {
  id: string;
  name: string;
  type: string;
  host: string;
  port: number;
  username: string;
  database: string;
  status: 'online' | 'offline' | 'error';
  createTime: string;
  updateTime: string;
}

const DatabaseConfigPage: React.FC = () => {
  const actionRef = useRef();
  const [drawerVisible, setDrawerVisible] = useState(false);
  const [editingRecord, setEditingRecord] = useState<DatabaseConfigItem | null>(null);
  const [selectedRowKeys, setSelectedRowKeys] = useState<string[]>([]);

  const handleDelete = async (id: string) => {
    const res = await DEL(`${DATABASE_CONFIG_URL}/${id}`);
    if (res.code === 200) {
      message.success('删除成功');
      actionRef.current?.reload();
    } else {
      message.error('删除失败');
    }
  };

  const handleBatchDelete = async () => {
    // 实现批量删除逻辑
    message.success(`已删除 ${selectedRowKeys.length} 条记录`);
    setSelectedRowKeys([]);
    actionRef.current?.reload();
  };

  const handleSyncStatus = async (id: string) => {
    // 实现同步状态逻辑
    message.success('状态已更新');
    actionRef.current?.reload();
  };

  const columns = [
    {
      title: '连接名称',
      dataIndex: 'name',
      key: 'name',
      render: (text: string) => <Link>{text}</Link>,
    },
    {
      title: '数据库类型',
      dataIndex: 'type',
      key: 'type',
      filters: [
        { text: 'MySQL', value: 'MySQL' },
        { text: 'PostgreSQL', value: 'PostgreSQL' },
        { text: 'Oracle', value: 'Oracle' },
        { text: 'SQL Server', value: 'SQLServer' },
      ],
    },
    {
      title: '主机',
      dataIndex: 'host',
      key: 'host',
    },
    {
      title: '端口',
      dataIndex: 'port',
      key: 'port',
    },
    {
      title: '用户名',
      dataIndex: 'username',
      key: 'username',
    },
    {
      title: '数据库',
      dataIndex: 'database',
      key: 'database',
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      valueEnum: {
        online: { text: '在线', status: 'Success' },
        offline: { text: '离线', status: 'Default' },
        error: { text: '错误', status: 'Error' },
      },
      render: (_, record) => (
        <Badge
          status={record.status === 'online' ? 'success' : record.status === 'offline' ? 'default' : 'error'}
          text={record.status === 'online' ? '在线' : record.status === 'offline' ? '离线' : '错误'}
        />
      ),
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record: DatabaseConfigItem) => (
        <Space size="middle">
          <Tooltip title="编辑">
            <Button
              type="link"
              icon={<EditOutlined />}
              onClick={() => {
                setEditingRecord(record);
                setDrawerVisible(true);
              }}
            />
          </Tooltip>
          <Tooltip title="删除">
            <Button
              type="link"
              danger
              icon={<DeleteOutlined />}
              onClick={() => handleDelete(record.id)}
            />
          </Tooltip>
          <Tooltip title="同步状态">
            <Button
              type="link"
              icon={<SyncOutlined />}
              onClick={() => handleSyncStatus(record.id)}
            />
          </Tooltip>
        </Space>
      ),
    },
  ];

  return (
    <PageContainer
      title={
        <Space>
          <Button
            icon={<ArrowLeftOutlined />}
            onClick={() => history.push('/')}
          >
            返回首页
          </Button>
          数据库连接管理
        </Space>
      }
      subTitle="管理和监控您的所有数据库连接"
      extra={[
        <Button key="1" type="primary" icon={<BarChartOutlined />}>
          数据库使用分析
        </Button>,
        <Tooltip key="2" title="了解如何管理数据库连接">
          <Button icon={<QuestionCircleOutlined />}>帮助</Button>
        </Tooltip>,
      ]}
    >
      <Card>
        <ProTable<DatabaseConfigItem>
          headerTitle="数据库连接列表"
          actionRef={actionRef}
          rowKey="id"
          search={{
            labelWidth: 'auto',
          }}
          toolBarRender={() => [
            <Button
              key="add"
              type="primary"
              icon={<PlusOutlined />}
              onClick={() => {
                setEditingRecord(null);
                setDrawerVisible(true);
              }}
            >
              新建连接
            </Button>,
            <Button
              key="batchDelete"
              danger
              disabled={selectedRowKeys.length === 0}
              onClick={handleBatchDelete}
            >
              批量删除
            </Button>,
          ]}
          request={async (params, sorter, filter) => {
            const { current, pageSize, ...restParams } = params;
            const res = await PAGE(DATABASE_CONFIG_URL, {
              page: current,
              limit: pageSize,
              ...restParams,
            }, sorter);
            if (res.code === 200 && res.data) {
              return {
                data: res.data.records,
                success: true,
                total: res.data.total,
              };
            }
            message.error('获取数据库配置信息失败');
            return { data: [], success: false };
          }}
          columns={columns}
          rowSelection={{
            selectedRowKeys,
            onChange: setSelectedRowKeys,
          }}
          pagination={{
            pageSize: 10,
          }}
          dateFormatter="string"
        />
      </Card>
      <Drawer
        title={editingRecord ? "编辑数据库连接" : "新建数据库连接"}
        placement="right"
        width={600}
        onClose={() => {
          setDrawerVisible(false);
          setEditingRecord(null);
        }}
        visible={drawerVisible}
      >
        <DatabaseConfigForm
          initialValues={editingRecord}
          onFinish={() => {
            setDrawerVisible(false);
            setEditingRecord(null);
            actionRef.current?.reload();
          }}
        />
      </Drawer>
    </PageContainer>
  );
};

export default DatabaseConfigPage;

